﻿/*
Library to support various functionality in the Mystery Foundation
http://sharepointmystery.com
Created by Christopher Kimbell
*/

Type.registerNamespace("SPM.ListManagement");

// create a class that allows us to send multiple document links
SPM.ListManagement.EmailLink = function () {
}
// determines if the link button should be enabled
SPM.ListManagement.EmailLink.IsAvailable = function () {
    var ctx = SP.ClientContext.get_current();
    return (SP.ListOperation.Selection.getSelectedItems(ctx).length > 0);
}
// handles a successful request from the server
SPM.ListManagement.EmailLink.HandleSuccess = function (result) 
{
    window.navigateMailToLinkWithMessage('', result.CreateLinkEmailBodyResult);
}
// handles a failed request from the server
SPM.ListManagement.EmailLink.HandleError = function (jqXhr, textStatus, errorThrown)
{
    alert(textStatus + ": " + errorThrown);
}
// initiates the creation of the email message
SPM.ListManagement.EmailLink.Create = function () 
{
    var ctx = SP.ClientContext.get_current();
    var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
    var web = ctx.get_web();
    var list = SP.ListOperation.Selection.getSelectedList();

    var documentIds = new Array();
    
    for(var i = 0; i < selectedItems.length; i++)
    {
        var item = selectedItems[i];
        if(item.fsObjType === "0")
        {
            documentIds.push(item.id);
        }
    }

    CallSPMService('GET',
        'CreateLinkEmailBody',
        'l=' + list + '&ids=' + documentIds.toString(),
        SPM.ListManagement.EmailLink.HandleSuccess,
        SPM.ListManagement.EmailLink.HandleError);
}

function CallSPMService(type, methodName, data, success, error)
{
    var ctx = SP.ClientContext.get_current();
    $.ajax(
    {
        type           : type, 
        url            : ctx.get_url() + "/_vti_bin/SPM/JavaScriptSupport.svc/" + methodName, 
        data           : data, 
        contentType    : "application/json; charset=utf-8",
        dataType       : "json",
        processdata    : true, 
        success        : success,
        error          : error
    });
}
